﻿#region 命名空间

using System;
using System.Web;

#endregion

namespace Sharp.Infrastructure
{
    /// <summary>
    ///     Cookies 处理类
    /// </summary>
    public class CookieHelper
    {
        /// <summary>
        ///     信息写入cookie
        /// </summary>
        /// <param name="key">cookie名 </param>
        /// <param name="value">cookie值 </param>
        /// <param name="timeout">过期时间,0表示cookie默认的过期时间 </param>
        public static void SetCookie(string key, string value, int timeout)
        {
            try
            {
                HttpCookie cookie = new HttpCookie(key) {Value = value};

                if (timeout != 0)
                    cookie.Expires = DateTime.Now.AddHours(Convert.ToInt32(timeout));

                HttpContext.Current.Response.Cookies.Add(cookie);
            }
            catch
            {
            }
        }

        /// <summary>
        ///     获得cookie
        /// </summary>
        /// <param name="key">cookie名 </param>
        /// <returns> </returns>
        public static string GetCookie(string key)
        {
            if (HttpContext.Current == null)
            {
                return null;
            }
            if (HttpContext.Current.Request.Cookies[key] == null)
                return null;
            else
                return HttpContext.Current.Request.Cookies[key].Value;
        }

        /// <summary>
        ///     获得cookie
        /// </summary>
        /// <param name="key">cookie名 </param>
        /// <returns> </returns>
        public static void KillCookie(string key)
        {
            HttpCookie cookie = new HttpCookie(key)
            {
                Expires = DateTime.Now.AddDays(-1.0)
            };
            HttpContext.Current.Response.Cookies.Add(cookie);
        }

        /// <summary>
        ///     判断cookie是否存在
        /// </summary>
        /// <param name="key">cookie名 </param>
        /// <returns> </returns>
        public static bool CheckCookie(string key)
        {
            return null != HttpContext.Current.Request.Cookies[key];
        }
    }
}